<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
      步骤：
        1. 获取 base64 字符串
        2. 提取 base64 字符串中的 MIME 类型和编码内容
        3. 将编码内容解码成二进制数据
        4. 创建 blob 对象
        5. 生成图片 url
        6. 创建下载链接并触发下载
      */

      function base64ToImageDownload(base64String, fileName = "download-img") {
        // 分割 base64 字符串以获取 MIME 类型和编码内容
        const parts = base64String.split(";base64,");
        const mimeType = parts[0].split(":")[1];
        const base64Encoded = parts[1];
        // 解码 base64 字符串
        const binaryString = atob(base64Encoded);
        // 将二进制字符串转换为 Unit8Array
        const len = binaryString.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        const byteArray = bytes.buffer;
        // 创建 blob 对象
        const blob = new Blob([byteArray], { type: mimeType });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `${fileName}.${mimeType.split("/")[1]}`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }

      // test
      const str =
        "";
      base64ToImageDownload(str, "img");
    </script>
  </body>
</html>
